package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Organization;
import com.example.exception.BusinessException;
import com.example.mapper.OrganizationMapper;
import com.example.service.OrganizationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;

@Service
@RequiredArgsConstructor
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {

    @Override
    @Transactional
    public boolean registerOrganization(Organization organization) {
        // 检查组织名称是否已存在
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Organization::getName, organization.getName());
        if (count(wrapper) > 0) {
            throw new BusinessException("组织名称已存在");
        }
        
        // 设置初始状态
        organization.setStatus(0);  // 待审核
        
        return save(organization);
    }

    @Override
    @Transactional
    public boolean updateOrganization(Organization organization) {
        // 检查组织是否存在
        Organization existingOrg = getById(organization.getId());
        if (existingOrg == null) {
            throw new BusinessException("组织不存在");
        }
        
        // 检查组织状态是否允许修改
        if (existingOrg.getStatus() == 2 || existingOrg.getStatus() == 3) {
            throw new BusinessException("当前状态不允许修改");
        }
        
        // 检查组织名称是否重复（排除自身）
        if (!existingOrg.getName().equals(organization.getName())) {
            LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Organization::getName, organization.getName())
                    .ne(Organization::getId, organization.getId());
            if (count(wrapper) > 0) {
                throw new BusinessException("组织名称已存在");
            }
        }
        
        return updateById(organization);
    }

    @Override
    @Transactional
    public boolean reviewOrganization(Long id, Integer status, String rejectReason, Long reviewerId) {
        // 检查组织是否存在
        Organization organization = getById(id);
        if (organization == null) {
            throw new BusinessException("组织不存在");
        }
        
        // 检查状态是否合法
        if (status < 0 || status > 3) {
            throw new BusinessException("状态值不合法");
        }
        
        // 更新审核信息
        organization.setStatus(status);
        organization.setRejectReason(rejectReason);
        organization.setReviewerId(reviewerId);
        organization.setReviewTime(LocalDateTime.now());
        
        return updateById(organization);
    }

    @Override
    @Transactional
    public boolean toggleOrganizationStatus(Long id, boolean enable) {
        // 检查组织是否存在
        Organization organization = getById(id);
        if (organization == null) {
            throw new BusinessException("组织不存在");
        }
        
        // 更新状态
        organization.setStatus(enable ? 1 : 3);  // 1-已审核 3-已禁用
        
        return updateById(organization);
    }

    @Override
    @Transactional
    public boolean deleteOrganization(Long id) {
        return removeById(id);
    }

    @Override
    @Transactional
    public boolean batchDeleteOrganizations(Long[] ids) {
        return removeByIds(Arrays.asList(ids));
    }

    @Override
    public Page<Organization> getOrganizationList(Integer pageNum, Integer pageSize, String keyword, 
            Integer type, Integer level, Integer status) {
        Page<Organization> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        if (StringUtils.hasText(keyword)) {
            wrapper.like(Organization::getName, keyword)
                    .or()
                    .like(Organization::getDescription, keyword);
        }
        if (type != null) {
            wrapper.eq(Organization::getType, type);
        }
        if (level != null) {
            wrapper.eq(Organization::getLevel, level);
        }
        if (status != null) {
            wrapper.eq(Organization::getStatus, status);
        }
        
        wrapper.orderByDesc(Organization::getCreateTime);
        return page(page, wrapper);
    }

    @Override
    public Organization getOrganizationInfo(Long id) {
        Organization organization = getById(id);
        if (organization == null) {
            throw new BusinessException("组织不存在");
        }
        return organization;
    }
} 